package com.zgq.share.ui.sina;

import weibo4android.Weibo;
import weibo4android.http.RequestToken;

import com.zgq.share.db.ShareInfoMananger;
import com.zgq.share.entity.ShareBean;
import com.zgq.share.thirdplatform.IPlatform;
import com.zgq.share.thirdplatform.PlatformDefs;
import com.zgq.share.thirdplatform.PlatformFactory;
import com.zgq.share.thirdplatform.PlatformType;
import com.zgq.share.thirdplatform.Session;
import com.zgq.share.tools.DialogTool;
import com.zgq.share.ui.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class SinaActivity extends Activity implements OnClickListener {
	
	private IPlatform p;
	private PlatformType pt;
	private ShareInfoMananger sm;
	
	private LinearLayout noLoginTip;
	private LinearLayout noveltyList;
	
	private Button btnLogin;
	
	private boolean isLogin = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sina_main);
		
		pt = PlatformType.SINA;
		p = PlatformFactory.getPlatform(this, pt);
		
		noLoginTip = (LinearLayout) findViewById(R.id.noLoginTip);
		noveltyList = (LinearLayout) findViewById(R.id.noveltyList);
		
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(this);
		
		changeShowView();
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		setIntent(intent);
		if (p == null) {
			return;
		}

		Session s = p.parseAuthResult(intent);
		if (s != null) {
			ShareBean share = new ShareBean();
			share.setName(pt.getName());
			share.setToken(s.getToken().getAccessToken());
			share.setSecret(s.getToken().getAccessTokenSecret());
			share.setSelected(true);

            sm.addShareInfo(share);
            isLogin = false;
            System.out.println("1--isLogin=" + isLogin);
            changeShowView();

		} else {
			Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
		}
		p = null;
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnLogin:
			p.authenticate();
			break;

		default:
			break;
		}
	}
	
	private void changeShowView() {
		if (isLogin) {
			sm = new ShareInfoMananger(this);
			ShareBean share = sm.getShareInfo(PlatformDefs.SINA_NAME);
			
			if (share == null) {
				noLoginTip.setVisibility(View.VISIBLE);
				DialogTool dialog = new DialogTool(this);
				dialog.showLoginTipDialog(R.string.app_name, R.string.app_name);
			}
		} else {
			noLoginTip.setVisibility(View.GONE);
			noveltyList.setVisibility(View.VISIBLE);
		}
	}
}
